package com.example.rabbitmq.provider;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class MQProvider {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("guest");
        factory.setPassword("guest");
        // 设置 RabbitMQ 地址
        factory.setHost("localhost");
        // 建立到代理服务器到连接
        // 获得信道
        try (Connection conn = factory.newConnection();
             Channel channel = conn.createChannel();) {
            // 声明交换器
            String exchangeName = "hello-exchange";
            channel.exchangeDeclare(exchangeName, "direct", true);
            String routingKey = "hello";
            // 发布消息
            byte[] messageBodyBytes = "hello-mq".getBytes();
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().contentType("text/plain").build();
            channel.basicPublish(exchangeName, routingKey, properties, messageBodyBytes);
            System.out.println("发送的消息是：" + new String(messageBodyBytes));
        }
    }
}
